package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.model.User;
import com.daoliuhe.scaffold.service.SessionService;
import com.daoliuhe.scaffold.core.RedisSessionDAO;
import com.daoliuhe.scaffold.tools.Constants;
import com.daoliuhe.scaffold.tools.MailUtil;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Service
public class SessionServiceImpl implements SessionService {

	private static final Logger logger = LoggerFactory.getLogger(SessionServiceImpl.class);

	@Autowired
	RedisSessionDAO sessionDAO;

    /***
     * 异步群发通知邮件
     * @param title  邮件主题
     * @param content  邮件内容
     */
	@Async
	@Override
	public void sendEmails(String title, String content) {
		logger.info("sendEmails: title:{}, content:{}", title, content);
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		Set<String> emails = new HashSet<String>();
		for (Session session : sessions) {
			User user = (User) session.getAttribute(Constants.USERINFO);
			if (null != user) {
				String email = user.getEmail();
				if (StringUtils.hasText(email)) {
					emails.add(email);
				}
			}
		}
		logger.info("sendEmails, emails:{}", emails.toString());
		for (String to : emails) {
			// 发送通知邮件
            MailUtil.sendMail(to, "", title, content, false);
			logger.info("send Email. to:{}, title:{}, content:{}", to, title, content);
		}
	}
}
